//
//  HZPhotoGroup.m
//  HZPhotoBrowser
//
//  Created by aier on 15-2-4.
//  Copyright (c) 2015年 GSD. All rights reserved.
//

#import "HZPhotoGroup.h"
#import "UIButton+WebCache.h"
#import "HZPhotoBrowser.h"

#define HZPhotoGroupImageMargin 15
#define PhotoMaxCount           9
#define PhotoW                  80
#define PhotoH                  PhotoW


@interface HZPhotoGroup () <HZPhotoBrowserDelegate>

@end

@implementation HZPhotoGroup 

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self setupSubViews];
    }
    return self;
}

- (instancetype)initWithCoder:(NSCoder *)coder
{
    self = [super initWithCoder:coder];
    if (self) {
        [self setupSubViews];
    }
    return self;
}

- (void)setupSubViews
{
    self.clipsToBounds = YES;
    
    for (int i = 0; i < PhotoMaxCount; i++) {
        UIButton *btn = [[UIButton alloc] init];
        
        btn.imageView.contentMode = UIViewContentModeScaleAspectFill;
        btn.clipsToBounds = YES;
        btn.tag = i;
        
        if (i < _photoItemArray.count) {
            NSString *url = _photoItemArray[i];
//            NSLog(@"url %@", url);
            [btn sd_setImageWithURL:[NSURL URLWithString:url] forState:UIControlStateNormal placeholderImage:[UIImage imageNamed:@"whiteplaceholder"]];
        }
        
        [btn addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:btn];
    }
}

- (void)setPhotoItemArray:(NSArray *)photoItemArray
{
    _photoItemArray = [photoItemArray copy];
    
    int imageCount = (int)_photoItemArray.count;
    [self.subviews enumerateObjectsUsingBlock:^(UIButton *btn, NSUInteger idx, BOOL *stop) {
        
        if (idx < imageCount) {
            btn.userInteractionEnabled = YES;
            [btn sd_setImageWithURL:[NSURL URLWithString:_photoItemArray[idx]] forState:UIControlStateNormal placeholderImage:[UIImage imageNamed:@"whiteplaceholder"]];
        } else {
            btn.userInteractionEnabled = NO;
            
        }
    }];
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    
    long imageCount = self.photoItemArray.count;
    int perRowImageCount = ((imageCount == 4) ? 2 : 3);
    int totalRowCount = ceil(imageCount / (CGFloat)perRowImageCount);
    // int totalRowCount = ((imageCount + perRowImageCount - 1) / perRowImageCount)
   
    [self.subviews enumerateObjectsUsingBlock:^(UIButton *btn, NSUInteger idx, BOOL *stop) {
        CGFloat w = PhotoW;
        CGFloat h = PhotoH;
        
        if (idx > imageCount) {
            w = 0;
            h = 0;
        }
        
        long rowIndex = idx / perRowImageCount;
        int columnIndex = idx % perRowImageCount;
        CGFloat x = columnIndex * (w + HZPhotoGroupImageMargin);
        CGFloat y = rowIndex * (h + HZPhotoGroupImageMargin);
        
        btn.frame = CGRectMake(x, y, w, h);
    }];
    
    self.frame = !imageCount ? CGRectZero : CGRectMake(0,
                                                       0,
                                                       self.bounds.size.width,
                                                       totalRowCount * (HZPhotoGroupImageMargin + PhotoH) - HZPhotoGroupImageMargin);
}


- (CGFloat)height
{
    long imageCount = self.photoItemArray.count;
    int perRowImageCount = ((imageCount == 4) ? 2 : 3);
    int totalRowCount = ceil(imageCount / (CGFloat)perRowImageCount);
    
    return totalRowCount * (HZPhotoGroupImageMargin + PhotoH) - HZPhotoGroupImageMargin;
}



- (void)buttonClick:(UIButton *)button
{
    //启动图片浏览器
    HZPhotoBrowser *browser = [[HZPhotoBrowser alloc] init];
    browser.sourceImagesContainerView = self; // 原图的父控件
    browser.imageCount = self.photoItemArray.count; // 图片总数
    browser.currentImageIndex = (int)button.tag;
    browser.delegate = self;
    [browser show];
    
}

#pragma mark - photobrowser代理方法

// 返回临时占位图片（即原来的小图）
- (UIImage *)photoBrowser:(HZPhotoBrowser *)browser placeholderImageForIndex:(NSInteger)index
{
    return [self.subviews[index] currentImage];
}


// 返回高质量图片的url
- (NSURL *)photoBrowser:(HZPhotoBrowser *)browser highQualityImageURLForIndex:(NSInteger)index
{
//    NSString *urlStr = [self.photoItemArray[index] stringByReplacingOccurrencesOfString:@"thumbnail" withString:@"bmiddle"];
    return [NSURL URLWithString:_photoItemArray[index]];
}

@end
